package com.tianyadu.mmall.validator;

import com.tianyadu.mmall.entity.SysUser;
import com.tianyadu.mmall.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.List;

/**
 * 自定义注解逻辑校验
 *
 * @author xueyj
 * @date 2019-09-20 23:06
 */
@Slf4j
public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {

    @Autowired
    private UserService userService;

    /**
     * 校验器初始化
     *
     * @param constraintAnnotation
     * @return void
     * @author xueyj
     * @date 2019/9/20-23:10
     */
    @Override
    public void initialize(MyConstraint constraintAnnotation) {
        System.out.println("my validator init");
    }

    /**
     * 执行校验
     *
     * @param value
     * @param context
     * @return boolean
     * @author xueyj
     * @date 2019/9/20-23:10
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        List<SysUser> sysUserList = userService.findAll();
        log.info("自定义注解业务逻辑查询全部用户信息，userInfoList = 【{}】", sysUserList);
        //  若用户信息为空，返回false(模拟自定义注解执行逻辑)
        if (CollectionUtils.isEmpty(sysUserList)) {
            return false;
        }
        return true;
    }
}